<?php
class resource_file_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('resource_file_row');
		$this->setModel('resource_file_model', 'file');
		$this->setModelCols('file', array('hash', 'type', 'size', 'extension', 'dimension', 'width', 'height', 'creationtime', 'lastupdate'));
	}

	public function save(resource_file_row $row) {
		if(!$row->getHash()) {
			throw new resource_exception("HASH Code ERROR.");
		}
		if(!preg_match('/^[0-9a-z]{32}$/is', $row->getHash())) {
			throw new resource_exception("HASH Code ERROR.");
		}
		$row->setSize(intval($row->get('size')));
		$row->setWidth(intval($row->get('width')));
		$row->setHeight(intval($row->get('height')));
		if(!$row->getSize() || !$row->getWidth() || !$row->getHeight()) {
			throw new resource_exception("FILE SIZE IS ZERO.");
		}
		$row->setDimension($row->getWidth() * $row->getHeight());
		$row->setExtension(trim($row->get('extension')));
		
		$where = array('hash = ?' => $row->getHash(), 'type = ?' => $row->getType()->getId());
		if($this->getModel('file')->fetchRow($where)) {
			$row->setLastupdate(system_date::timestamp());
			$this->getModel('file')->update($row->getModelData('file'), $where);
		} else {
			$row->setCreationtime(system_date::timestamp());
			$row->setLastupdate(system_date::timestamp());
			$this->getModel('file')->insert($row->getModelData('file'));
		}
		return $row;
	}
	
	public function delete($row) {
		return ;
	}

}